<?php
// digiboard by digitalboom.org
// http://www.digitalboom.org
//
// Information Technology program
// Sirindhorn International Institute of Technology
// Thammasat University, Rangsit Campus
// http://www.siit.tu.ac.th
//
// authors: bact', pa+, hoho, BiGGA
// first created on: 2002 Jun xx
// last modified on: 2003 Nov 20
// last modified by: bact'

include_once("settings/config.inc.php");
include_once("settings/forum.inc.php");
include_once("settings/accounts.inc.php");
include_once("lib/feedcreator.class.php");
include_once("lib/util.inc.php");

$tp = array(
 "total_topics" => 0,
 "total_pages"  => 0,
);

$dblink = null;
$errmsg = "";
$sql_errmsg = "";

function topiclist_print_error() {
 global $DGB, $errmsg, $sql_errmsg;

 echo<<<EOT
<tr class="lsRowOdd">
 <td colspan=8>
  <b>Last error message:</b><br>$errmsg
 </td>
</tr>
EOT;
 if ($DGB['DISPLAY_SQL_ERRMSG']) {
  if ($sql_errmsg == "")
   $sql_errmsg = "(no sql error message)";

  echo<<<EOT
<tr class="lsRowEven">
 <td colspan=8>
  <b>Last SQL server error message:</b><br>$sql_errmsg
 </td>
</tr>
EOT;
 }
}

function topiclist_total_topics() {
 global $tp;
 return $tp['total_topics'];
}

function topiclist_total_pages() {
 global $tp;
 return $tp['total_pages'];
}

function topiclist_prepare($forum, $sortby, $order, $page, $perpage, $keyword) {
 global $tp, $DGB, $db_link, $errmsg, $sql_errmsg, $DGB_FORUM, $DGB_FORUM_PUBLIC;

 $keyword = mysql_escape_string($keyword);
 
 $db_link = dgb_db_connect();
 if ($db_link != false) {
  $q_tail = " FROM ".$DGB['DB_TOPICS_TABLE']." WHERE STATUS<>0";

  switch ($forum) {
   case -1: // ALL
    // Spam & Trash
    $q_tail.=" AND FORUM_ID<>25 AND FORUM_ID<>26 ";
    break;
   case 0: // GENERAL
    // skip $DGB_FORUM_PUBLIC[n] = 0
    $skip_forum = "";
    for ($fn=1; $fn <= $DGB_FORUM["NUMBER"]; $fn++) {
     if ($DGB_FORUM_PUBLIC[$fn] == 0) {
      $skip_forum.= " AND FORUM_ID<>$fn ";
     }
    }
    $q_tail.=$skip_forum;

    // Spam & Trash
    $q_tail.=" AND FORUM_ID<>25 AND FORUM_ID<>26 ";
    break;
   default:
    // also show announcements ?
    if ($DGB["ENABLE_FORCEANNOUNCEMENT"]) {
     $q_tail.=" AND (FORUM_ID=$forum OR FORUM_ID=1)";
    } else {
     $q_tail.=" AND FORUM_ID=$forum";
    }
  }

// start Search
// by Pa+ it://3 (krissdap@hotmail.com)
  if ($keyword!='')
  {
    // Search for Match from wb_answers
    $searchquery="SELECT Topic_ID FROM ".$DGB['DB_ANSWERS_TABLE']." WHERE (Message LIKE '%$keyword%' OR PosterName LIKE '%$keyword%')";
    $searchresult = mysql_query($searchquery);
    // $topiclist is a string contains Topic_ID which have matching pattern.
    // I set it to zero, in case that no match is found.
    $topiclist=0;
    if (mysql_num_rows($searchresult)>0)
    {
      $row=mysql_fetch_array($searchresult);
        $topiclist=$row['Topic_ID'];
      while($row = mysql_fetch_array($searchresult))
        $topiclist.=",".$row['Topic_ID'];
    }
    //  $q_tail.=" AND (Topic_ID IN ($topiclist))";  // Search in wb_answers
    //  $q_tail.=" AND ((Message LIKE '%$keyword%') OR (PosterName LIKE '%$keyword%') OR (Title LIKE '%$keyword%'))";  // search in wb_topics
    $q_tail.=" AND (Message LIKE '%$keyword%' OR PosterName LIKE '%$keyword%' OR Title LIKE '%$keyword%' OR Topic_ID IN ($topiclist))";  // search in both
    mysql_free_result($searchresult);
  }
// end Search

  if ($sortby == "PostTime")
   $q_tail.=" ORDER BY Topic_ID";
  else
   $q_tail.=" ORDER BY $sortby";

  $q_tail.=" $order";

  $query = "SELECT COUNT(*)".$q_tail;
  $result = mysql_query($query);
  if ($result) {
   $data = mysql_fetch_row($result);
   $tp['total_topics'] = $data[0];

   mysql_free_result($result);

   if ($tp['total_topics'] > 0) {
    // calculates pages
    $tp['total_pages'] = floor($tp['total_topics'] / $perpage);
    if (($tp['total_topics'] % $perpage) != 0) {
     $tp['total_pages'] = $tp['total_pages'] + 1;
    }
    if ($page > $tp['total_pages']) {
     topiclist_print_error("Page number specified out of range, last page displayed.");
     $page = $tp['total_pages'];
    }
    $row_offset = ($page-1) * $perpage;

    $query = "SELECT *".$q_tail;
    $query.=" LIMIT $row_offset, $perpage";
    $result = mysql_query($query);

    return $result;
   } else {
    $errmsg.= "No topic found.<br>";
    $sql_errmsg.="SQL Query: \"".$query."\" gives<br>".mysql_error()."<br>";
    return false;
   }
  } else {
    $errmsg.="Have a problem with view selection.<br>";
    $sql_errmsg.="SQL Query: \"".$query."\" gives<br>".mysql_error()."<br>";
   return false;
  }
 } else {
  $errmsg.="Cannot connect to database, try again in few minutes.<br>
   If it still has a problem, please contact <a href=\"mailto:".$DGB['ADMIN_EMAIL']
   ."\">administrator</a>. Thank you.<br>";
  return false;
 }
}

function topiclist_print_each($result_row, $row_style,$IsSticky) {
 global $NowTimeStamp_Offsetted, $DGB_FORUM_NAME, $DGB,  $db_link;

 $Topic_ID   = $result_row['Topic_ID'];
 $Forum_ID   = $result_row['Forum_ID'];
 $Status     = $result_row['Status'];
 $Title      = htmlspecialchars(stripslashes($result_row['Title']));
 
 if(strlen($Title) > $DGB["TITLE_LENGTH_LIMIT"]) {
   $Title = substr($Title, 0, $DGB["TITLE_LENGTH_LIMIT"]-4)." &hellip;";
 }
 // trim off very long poster name
 $PosterName = str_replace("[RegisterUserLogin]","",$result_row['PosterName']);
 $PosterName = substr($PosterName, 0, $DGB["POSTERNAME_LENGTH_LIMIT"] );
 $PosterName = stripslashes($PosterName);

 $ReadNum    = $result_row['ReadNum'];
 $AnsNum     = $result_row['AnsNum'];

 $PostTime   = $result_row['PostTime'];
 $AnsTime    = $result_row['AnsTime'];
 
 $ExContent	 = $result_row['ExplicitContent'];

 // generate appropiate time showers
 $PostTimeStamp = mysql_datetime_to_timestamp($PostTime);
 $AnsTimeStamp  = mysql_datetime_to_timestamp($AnsTime);

 $PostTime = time_display($PostTimeStamp, $NowTimeStamp_Offsetted);
 $AnsTime  = ($AnsNum==0) ? "--" : time_display($AnsTimeStamp , $NowTimeStamp_Offsetted); //edited by mameou

 // make forum icon
 if($ExContent == 1) {
  $ForumIcon = "<img src=\"images/explicit_content.gif\" alt=\"".$DGB_FORUM_NAME[$Forum_ID]." / explicit content\" title=\"".$DGB_FORUM_NAME[$Forum_ID]." / explicit content\" width=\"16\" height=\"16\">";
 }
 else if($IsSticky == 1) 
{
	//if sticky, use (y) icon 
 $ForumIcon = "<img src=\"images/sticky.gif\" title=\"Sticky Topic\" alt=\"Sticky Topic\" width=\"16\" height=\"16\">";
  }
 else {
  $ForumIcon = forum_icon($Forum_ID, $AnsNum, $ReadNum, $PostTimeStamp, $AnsTimeStamp, $NowTimeStamp_Offsetted);
  $ForumIcon = "<img src=\"$ForumIcon\" title=\"".$DGB_FORUM_NAME[$Forum_ID]."\" alt=\"".$DGB_FORUM_NAME[$Forum_ID]."\" width=\"16\" height=\"16\">";
 }
 
 //if sticky, print [!] before title
 if($IsSticky == 1) {
  //$Title = "<font size=\"-2\" color=\"#FF0000\"><b>!!</b> </font>$Title";
  $Title = "<span id=\"stickyTopic\">!!</span>&nbsp;$Title";
 }

//Select newest poster name
$sqlCmd = "SELECT PosterName FROM ".$DGB['DB_ANSWERS_TABLE'].
  " WHERE Topic_ID=".$result_row['Topic_ID']." Order By PostTime Desc Limit 0,1";
$result = mysql_query($sqlCmd,$db_link);
$num = mysql_num_rows($result);

 if($num > 0) {
  //have answer 
	$data = mysql_fetch_array($result);
	$AnswerPosterName = str_replace("[RegisterUserLogin]","",$data['PosterName']);
	$AnswerPosterName = substr($AnswerPosterName, 0, $DGB["POSTERNAME_LENGTH_LIMIT"] );
	$AnswerPosterName = stripslashes($AnswerPosterName);
 } else {
  $AnswerPosterName = "";
 }


 echo<<<EOT
<tr class="$row_style"
onMouseOver="this.className='lsRowMouseOver'; return true"
onMouseOut="this.className='$row_style'; return true"
onClick="this.children.tags('TD')[2].children.tags('A')[0].click(); return true">
 <td class="lsID"><font size=-2>$Topic_ID</font></td>
 <td class="lsForum">$ForumIcon</td>
 <td class="lsTitle"><a href="read.php?Topic_ID=$Topic_ID" target="_blank">$Title</a></td>
 <td class="lsPost"><font size=-2>$PostTime<br><font color=green>$PosterName</font></font></td>
 <td class="lsUpdate"><font size=-2>$AnsTime<br><font color=green>$AnswerPosterName</font></font></td>
 <td class="lsRead">$ReadNum</td>
 <td class="lsAns">$AnsNum</td>
</tr>
EOT;
}

function topiclist_print($result) {
 global $errmsg, $sql_errmsg;

 if ($result) {
  $row_style = "lsRowOdd";
  $IsSticky = 0; // This is Sticky Topic  1 = true, 0 = false
  if (mysql_num_rows($result)) {
   while($row = mysql_fetch_array($result)) {
    topiclist_print_each($row, $row_style,$IsSticky);
    $row_style = ($row_style=="lsRowOdd") ? "lsRowEven" : "lsRowOdd";
   }
  } else {
   $errmsg.="No topic found.<br>";
   $sql_errmsg.="SQL Query: \"".$query."\" gives<br>".mysql_error()."<br>";

  }
 } else {
  $errmsg.="Have a problem with view selection.<br>";
  $sql_errmsg.="SQL Query: \"".$query."\" gives<br>".mysql_error()."<br>";
 }

 if ($errmsg != "")
  topiclist_print_error($errmsg);
}

function page_selector($total_pages, $curpage=1) {
 $html = "<select class=\"mb\" name=\"page\" onChange=\"reload_list_with_keyword();\">\n";
 for ($i = 1; $i <= $total_pages; $i++) {
  if ($i == $curpage)
   $html .= "<option value=\"$i\" selected>$i</option>\n";
  else
   $html .= "<option value=\"$i\">$i</option>\n";
 }
 $html .= "</select>\n";

 return $html;
}

function perpage_selector($curperpage, $step, $max) {
 $html = "<select class=\"mb\" name=\"ppage\" onChange=\"reload_list_with_keyword();\">\n";
 $i = 0;
 if (($i < $curperpage) && ($i+$step > $curperpage))
  $html .="<option value=\"$curperpage\" selected>$curperpage</option>\n";
 for ($i = $step; $i <= $max; $i=$i+$step) {
  if ($i == $curperpage) {
   $html .= "<option value=\"$i\" selected>$i</option>\n";
  } else {
   $html .= "<option value=\"$i\">$i</option>\n";
   if (($i < $curperpage) && ($i+$step > $curperpage))
    $html .="<option value=\"$curperpage\" selected>$curperpage</option>\n";
  }
 }
 if ($i < $curperpage)
  $html .="<option value=\"$curperpage\" selected>$curperpage</option>\n";

 $html .= "</select>\n";

 return $html;
}

function forum_list($forum,$sortby,$ppage) {
 global $DGB_FORUM_NAME, $DGB_LISTED_FORUM_NUMBER, $DGB_LISTED_FORUM;
 $html = "";
 
 for ($i=1; $i <= $DGB_LISTED_FORUM_NUMBER; $i++) {
  $iforum = $DGB_LISTED_FORUM[$i];
  
  if ($iforum == $forum) {
   $html.= "<td class=\"mbMouseOver\">".$DGB_FORUM_NAME[$iforum]."</td>\n";
  } else {
   $link = "list.php?forum=$iforum&sortby=$sortby&ppage=$ppage";
   $html.= "<td onMouseOver=\"this.className='mbMouseOver'; return true\"";
   $html.= "onMouseOut=\"this.className='mb'; return true\"";
   $html.= "onClick=\"document.location.href='$link';\">";
   $html.= "<a class=\"mb\" href=\"$link\">".$DGB_FORUM_NAME[$iforum]."</a></td>\n";
  }
 }
 return $html;
}

function forum_selector($forum) {
 global $DGB_FORUM, $DGB_FORUM_NAME, $DGB_FORUM_PUBLIC;

 $html = "<select class=\"pHead\" name=\"forum\" onChange=\"reload_list_without_keyword();\">\n";
 if ($forum == -1)
  $html.= "<option value=\"-1\" selected>ALL</option>\n";
 else
  $html.= "<option value=\"-1\">ALL</option>\n";

 if ($forum == 0)
  $html.= "<option value=\"0\" selected>GENERAL</option>\n";
 else
  $html.= "<option value=\"0\">GENERAL</option>\n";

 for ($i = 1; $i <= $DGB_FORUM['NUMBER']; $i++) {
  if ($i == $forum) {
   $html .= "<option value=\"$i\" selected>".$DGB_FORUM_NAME[$i];
  } else {
   $html .= "<option value=\"$i\">".$DGB_FORUM_NAME[$i];
  }
  if ($DGB_FORUM_PUBLIC[$i] == 0) {
   $html .= " *";
  }
  $html .= "</option>\n";
 }
 $html .= "</select>\n";

 return $html;
}

function sortby_selector($sortby=0) {
 $sorttype_num = 4;
 $ss[0] = "PostTime";
 $ss[1] = "AnsTime";
 $ss[2] = "ReadNum";
 $ss[3] = "AnsNum";

 $html = "<select class=\"mb\" name=\"sortby\" onChange=\"reload_list_with_keyword();\">\n";

 for ($i = 0; $i < $sorttype_num; $i++) {
  if ($ss[$i] == $sortby)
   $html .= "<option value=\"".$ss[$i]."\" selected>".$ss[$i]."</option>\n";
  else
   $html .= "<option value=\"".$ss[$i]."\">".$ss[$i]."</option>\n";
 }
 $html .= "</select>\n";

 return $html;
}


//==== STICKY TOPIC SECTION ============

function sticky_topiclist_print($Sticky_TopicID,$Sticky_Num) {
 global $DGB, $db_link, $errmsg, $sql_errmsg, $DGB_FORUM, $DGB_FORUM_PUBLIC;

 $db_link = dgb_db_connect();

 if ($Sticky_TopicID) {
  $ModValue = $Sticky_Num % 2;
  $row_style = ($ModValue == 0) ? "lsRowOdd" : "lsRowEven";
  
  $sqlCmd = "SELECT * FROM ".$DGB['DB_TOPICS_TABLE']." WHERE STATUS<>0 AND Topic_ID ='$Sticky_TopicID' ORDER BY Topic_ID DESC ";
  $result = mysql_query($sqlCmd,$db_link);
  $IsSticky = 1; // This is Sticky Topic  1 = true, 0 = false
  if (mysql_num_rows($result)) {
   while ($row = mysql_fetch_array($result)) {
    topiclist_print_each($row, $row_style, $IsSticky);
    $row_style = ($row_style == "lsRowOdd") ? "lsRowEven" : "lsRowOdd";
   }
  } else {
   $errmsg.="No topic found.<br>";
   //$sql_errmsg.="SQL Query: \"".$query."\" gives<br>".mysql_error()."<br>";
  }
 } else {
  $errmsg.="Have a problem with view selection.<br>";
  //$sql_errmsg.="SQL Query: \"".$query."\" gives<br>".mysql_error()."<br>";
 }

 if ($errmsg != "")
  topiclist_print_error($errmsg);
}

// make RSS feed
function makefeed_list($item_limit, $msg_limit) {
  global $DGB, $db_link;

  $rss = new UniversalFeedCreator("RSS2.0");
  $rss->useCached();
  $rss->title = "SIIT.NET new posts";
  $rss->description = "new posts from SIIT.NET webboard";
  $rss->link = "http://siit.net/webboard/";
  $rss->syndicationURL = "http://siit.net/".$PHP_SELF;
  
  $result = topiclist_prepare(-1, "PostTime", "DESC", 1, $item_limit, "");
  while ($data = mysql_fetch_object($result)) {
   $item = new FeedItem();
   
   $Title = htmlspecialchars(stripslashes($data->Title));
   $item->title = iconv("TIS-620", "UTF-8", $Title);
   
   $item->link = "http://siit.net/webboard/read.php?Topic_ID=".$data->Topic_ID;
   $item->date = $data->PostTime;
   $item->source = "http://siit.net/webboard/";
   
   // trim off very long poster name
   $PosterName = str_replace("[RegisterUserLogin]","",$data->PosterName);
   $PosterName = stripslashes($PosterName);
   $item->author = iconv("TIS-620", "UTF-8", $PosterName);
   
   $Message = "a topic with topic number specified was not found or has been deleted.";
   $desc_query = "SELECT Message FROM ".$DGB['DB_TOPICS_TABLE']." WHERE Topic_ID=".$data->Topic_ID." AND Status<>0";
   $db_link = dgb_db_connect();
   $desc_result = mysql_query($desc_query, $db_link);
   if ($desc = mysql_fetch_object($desc_result)) {
     $Message   = stripslashes($desc->Message);
     //$Message   = nl2br($Message);
     $Message   = bbcodeparse($Message);
	 $Message   = trim($Message);
     if(strlen($Message) > $msg_limit)
	  $Message = substr($Message, 0, $msg_limit-4)." ...";
   }
   $item->description = iconv("TIS-620", "UTF-8", $Message);
   
   $rss->addItem($item);
  }
  
  $rss->saveFeed("RSS2.0", "feed/rss.xml", false);
}
?>
